package com.xiaoming.backend.service.impl;

import com.xiaoming.backend.dao.ICarTaskDao;
import com.xiaoming.backend.dao.IOrderDao;
import com.xiaoming.backend.dto.request.TaskRequest;
import com.xiaoming.backend.dto.response.TaskResponse;
import com.xiaoming.backend.entity.db.po.CarTaskPO;
import com.xiaoming.backend.entity.orm.Task;
import com.xiaoming.backend.entity.orm.User;
import com.xiaoming.backend.service.ITaskService;
import com.xiaoming.backend.util.DeepCopyUtil;
import com.xiaoming.backend.util.StringUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
@Slf4j
public class TaskServiceImpl implements ITaskService {

    private final ICarTaskDao taskDao;

    private final IOrderDao orderDao;

    @Override
    public List<TaskResponse> findTasks(User user, TaskRequest taskRequest) {
        int flag = 1;
        String status = null;
        Long userId = user.getUserId();
        if (StringUtil.equals("", taskRequest.getDriverId()) || taskRequest.getDriverId()==null){
            flag = 0;
        }
        if (!"".equals(taskRequest.getStatus())){
            status = taskRequest.getStatus();
        }
        if (User.ADMIN.equals(user.getRole())){
            userId = null;
        }
        List<Task> taskInfo = taskDao.getTaskInfo(userId, flag, status, user.getFacilityId());
        return taskInfo.stream()
                .map(po -> DeepCopyUtil.copyByJackson(po, TaskResponse.class))
                .collect(Collectors.toList());
    }

    @Override
    @Transactional
    public String startTask(User user, TaskRequest taskRequest) {
        log.info("开始运输任务：{}。。。。。。。。",taskRequest.getTaskId());
        String status = "运输中";
        if (!"".equals(taskRequest.getStatus()) && taskRequest.getStatus() != null){
            status = taskRequest.getStatus();
        }
        CarTaskPO carTaskPO = taskDao.startTask(Long.valueOf(taskRequest.getTaskId()), status, Long.valueOf(taskRequest.getEndFacilityId()), user.getUserId());

        int i = orderDao.uptWaste(Math.toIntExact(carTaskPO.getOrderId()), status, null, "", "0", null, Long.valueOf(taskRequest.getEndFacilityId()), null,null);

        return "任务开始运输";
    }

    @Override
    @Transactional
    public int finishTask(User user, TaskRequest taskRequest) {
        String status = "已完成";
        if (!"".equals(taskRequest.getStatus()) && taskRequest.getStatus() != null){
            status = taskRequest.getStatus();
        }
        Integer orderId = taskDao.finishTask(Long.valueOf(taskRequest.getTaskId()), status);

        return orderDao.uptWaste(orderId, "待处理", null, "", "0",null, null, null,null);

    }
}
